package io.renren.modules.sys.controller;


import com.yisoo.common.vo.UserVo;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.form.SysLoginForm;
import io.renren.modules.sys.service.SysCaptchaService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

@RestController
public class YiooController {

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Autowired
    SysUserService sysUserService;

    /***
     * 根据token 获取id
     //	 * @param token
     * @return
     */
    @GetMapping("/yisoo/getuserid/{token}")
    public R getUseridByToken(@PathVariable("token") String token){
//        System.out.println("==");
        return sysUserTokenService.getUserIdByToken(token);
    }

    @GetMapping("/yisoo/info/{userid}")
    public R info(@PathVariable("userid") String userid){
//        System.out.println("==");
        SysUserEntity userEntity = sysUserService.getById(userid);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userEntity,userVo);
        return R.ok().put("data",userVo);
    }
    /**
     * 登录
     */
    @PostMapping("/yisoo/login")
    public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException {
        //跳过验证码验证
//        boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
//        if(!captcha){
//            return R.error("验证码不正确");
//        }
        //用户信息
        SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

        //账号不存在、密码错误
        if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
            return R.error("账号或密码不正确");
        }

        //账号锁定
        if(user.getStatus() == 0){
            return R.error("账号已被锁定,请联系管理员");
        }

        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(user.getUserId());
        return r;
    }
    @PostMapping("/yisoo/reg")
    public R save(@RequestBody SysUserEntity user){
        System.out.println(user);
        ValidatorUtils.validateEntity(user, AddGroup.class);
//
//        user.setCreateUserId(getUserId());
       sysUserService.saveUser(user);
        //用户信息
        SysUserEntity userEntity = sysUserService.queryByUserName(user.getUsername());
        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(userEntity.getUserId());
        return r;
    }
}
